package com.atguigu.lease.web.app.service.impl;


import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {


    @Autowired
    private Client client;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private UserInfoService userInfoService;

    @Override
    public void sendCode(String phone) throws Exception {
        /*//设置key
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        //检查是否存在
        Boolean iskey = redisTemplate.hasKey(key);
        //判断验证码是否存在
        if (iskey) {
            //过期时间内频繁发送
            throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
        }
        //发送验证码
        String code = "";
        Random random = new Random();
        for (int i = 0; i < 4; i++) {
            code += random.nextInt(10);
        }
        System.out.println("code = " + code);
        //固定步骤
        SendSmsRequest sendSmsRequest = new SendSmsRequest();
        //设置手机号
        sendSmsRequest.setPhoneNumbers(phone);
        //设置阿里云短信名
        sendSmsRequest.setSignName("阿里云短信测试");
        sendSmsRequest.setTemplateCode("SMS_154950909");
        sendSmsRequest.setTemplateParam("{\"code\":\"" + code + "\"}\n");
        client.sendSms(sendSmsRequest);
        //将验证码存储+phone作为key存储到redis中
        redisTemplate.opsForValue().set(key, code, RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);*/





        //设置key
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        //判断redis中是否有验证码
        boolean iskey = redisTemplate.hasKey(key);
        if(iskey){
            throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
        }
        //发送验证码
        String code="";
        //随机验证码
        Random random = new Random();
        for(int i=0;i<6;i++){
            code+=random.nextInt(10);
        }
        //控制台输出验证码
        System.out.println("code = " + code);
        //设置短信
        SendSmsRequest smsRequest = new SendSmsRequest();
        smsRequest.setSignName("阿里云短信测试");
        smsRequest.setPhoneNumbers(phone);
        smsRequest.setTemplateCode("SMS_154950909");
        smsRequest.setTemplateParam("{\"code\":\"" + code + "\"}\n");
        client.sendSms(smsRequest);
        //验证码加到redis中
        redisTemplate.opsForValue().set(key,code,RedisConstant.APP_LOGIN_CODE_TTL_SEC,TimeUnit.SECONDS);

    }

    //登录
    @Override
    public String login(LoginVo loginVo) {
        //检查手机号是否存在
        if(ObjectUtils.isEmpty(loginVo.getPhone())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        //检查驶入的验证码是否存在
        if(ObjectUtils.isEmpty(loginVo.getCode())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }
        //检验验证码
        //判断redis中的验证码是否为null，为null返回为过期
        String key = RedisConstant.APP_LOGIN_PREFIX + loginVo.getPhone();
        if (!redisTemplate.hasKey(key)) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }
        //判断前端传过来的code和redis中的code是否相等，相等
        if(!redisTemplate.opsForValue().get(key).equals(loginVo.getCode())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR    );
        }
        //查看当前账号的状态
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserInfo::getPhone,loginVo.getPhone());
        UserInfo userInfo = userInfoService.getOne(queryWrapper);
        if(userInfo==null){
            //注册
            userInfo = new UserInfo();
            //设置当前手机号为注册后的手机号
            userInfo.setPhone(loginVo.getPhone());
            //设置当前账号的状态
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfo.setNickname(""+loginVo.getPhone().substring(5));
            userInfoService.save(userInfo);
        }
        //不是注册的话，那就查看当前手机号账号的状态，禁用不能登录
        if(userInfo.getStatus()==BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
        //创建并且返回token
        return JwtUtil.createToken(userInfo.getId(),loginVo.getPhone());
    }
}
